<script setup>
import {ref} from "vue";
import {addArticleCategory, editArticleCategory} from "@/api/article.js";

const dialogVisible = ref(false)
const formModel = ref({
	cateName: '',
	cateAlias: ''
})
const rules = {
	cateName: [
		{required: true, message: "请输入分类名称", trigger: "blur"},
		{pattern: /^\S{1,10}$/, message: "分类名称必须是 1-10 位非空字符", trigger: "blur"}
	],
	cateAlias: [
		{required: true, message: "请输入分类别名", trigger: "blur"},
		{pattern: /^[a-zA-Z0-9]{1,15}$/, message: "分类别名必须是 1-10 位的字母或数字", trigger: "blur"}
	]
}
const formRef = ref()

const open = (row) => {
	dialogVisible.value = true
	// 添加=重置表单内容，编辑=填充表单内容
	formModel.value = {...row}
}

const emit = defineEmits(['success'])

const onSubmit = async () => {
	await formRef.value.validate()
	const isEdit = formModel.value.id
	if (isEdit) {
		await editArticleCategory(formModel.value)
		ElMessage.success("编辑成功")
	} else {
		await addArticleCategory(formModel.value)
		ElMessage.success("添加成功")
	}
	dialogVisible.value = false
	// 通知父组件刷新一下数据
	emit('success')
}

// 向外暴露方法
defineExpose({open})
</script>

<template>
	<el-dialog v-model="dialogVisible" :title="formModel.id ? '编辑分类' : '添加分类'" width="30%">
		<el-form
				ref="formRef"
				:model="formModel"
				:rules="rules"
				label-width="100px" style="padding-right: 30px">
			<el-form-item label="分类名称：" prop="cateName">
				<el-input placeholder="请输入分类名称" v-model="formModel.cateName"/>
			</el-form-item>
			<el-form-item label="分类别名：" prop="cateAlias">
				<el-input placeholder="请输入分类别名" v-model="formModel.cateAlias"/>
			</el-form-item>
		</el-form>
		<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="onSubmit">
						确 定
					</el-button>
				</span>
		</template>
	</el-dialog>
</template>

<style scoped>

</style>